/*
 * Copyright 2010 by IPS. Floor 3,Universal Industrial Building, 
 * Tian Yaoqiao Road 1178,Shanghai, P.R. China，200300. All rights reserved.
 *
 * This software is the confidential and proprietary information of IPS
 * ("Confidential Information"). You shall not disclose such
 * Confidential Information and shall use it only in accordance with the terms
 * of the license agreement you entered into with IPS.
 */
package com.axis2.web.listener;

import com.axis2.common.util.SocketHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.net.Socket;

/**
 * 
 * @ClassName: CommServerListener
 * @Description: 通讯前置监听服务
 * @author 杨莹辉
 * @version 2016-04-18
 * 
 */
public class CommServerListener implements ServletContextListener {
	/**
	 * 日志对象
	 */
	private static Logger logger = LoggerFactory.getLogger(CommServerListener.class);
	
	private static SocketHelper socketHelper = null;
	/**
	 * 
	 */
	public CommServerListener() {
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.info("服务器重启………………");
		if(socketHelper !=null){
			Socket socket = socketHelper.getSocket();
			if(socket != null){
				try {
					logger.info("销毁了Context destroyed socket on " + socket);
					socket.close();
				} catch (IOException e) {
					logger.error("Context destroyed IOException",e);
				}
			}
			socketHelper.setCanRun(false);
			Thread checkThread = socketHelper.getCheckThread();
			if(checkThread !=null){
				logger.info("销毁了Context destroyed socket on checkThread ");
				checkThread.stop();
			}
			Thread sendThread =socketHelper.getSendThread() ;
			if(sendThread !=null){
				logger.info("销毁了Context destroyed socket on  sendThread");
				sendThread.stop();
			}
			Thread receiveThread=socketHelper.getReceiveThread();
			if(receiveThread !=null){
				logger.info("销毁了Context destroyed socket on receiveThread ");
				receiveThread.stop();
			}
		}
		
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextInitialized(ServletContextEvent arg0) {		
		socketHelper = SocketHelper.getInstance();
		socketHelper.setCanRun(true);
	}

}
